#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath> // For std::abs

using namespace std;

class Solution 
{
public:
    vector<int> sortedSquares(vector<int>& nums) 
    {
        int size = nums.size();
        vector<int> result(size); // 构造函数直接预留空间
        // result.resize(size);
        int left_ptr = 0;
        int right_ptr = size - 1;
        int write_ptr = right_ptr;
        while(left_ptr <= right_ptr)
        {
            int right_square = nums[right_ptr] * nums[right_ptr];
            int left_square = nums[left_ptr] * nums[left_ptr];
            if (right_square >= left_square)
            {
                result[write_ptr] = right_square;
                write_ptr--;
                right_ptr--;
            }
            else
            {
                result[write_ptr] = left_square;
                write_ptr--;
                left_ptr++;
            }
        }
        return result;
    }
};

int main()
{
    Solution s;
    
    // 测试案例1：包含正数和负数的数组
    vector<int> nums1 = {-4, -1, 0, 3, 10};
    cout << "原始数组: ";
    for(int num : nums1) {
        cout << num << " ";
    }
    cout << endl;
    
    vector<int> result1 = s.sortedSquares(nums1);
    cout << "平方后排序: ";
    for(int num : result1) {
        cout << num << " ";
    }
    cout << endl; // 输出: 0 1 9 16 100
    
    // 测试案例2：全为负数的数组
    vector<int> nums2 = {-7, -3, -2, -1};
    cout << "\n原始数组: ";
    for(int num : nums2) {
        cout << num << " ";
    }
    cout << endl;
    
    vector<int> result2 = s.sortedSquares(nums2);
    cout << "平方后排序: ";
    for(int num : result2) {
        cout << num << " ";
    }
    cout << endl; // 输出: 1 4 9 49
    
    return 0;
}
